import cherrypy
import citibank
import model
import util
from BeautifulSoup import BeautifulSoup, Tag
from UIBase import UIBase
from Cheetah.Template import Template
from schema import session, schema
from svg.charts import bar
from svg.charts import time_series

from datetime import datetime, timedelta
class UIChart(UIBase):
    def __init__(self):
        UIBase.__init__(self)
        self.template_chart_mount = 'template_chart_mount.tmp'

    def create_graph_plot(self, data, meses):
        fields = meses
        g = bar.VerticalBar(fields)
        g.stack = 'side'
        g.scale_integers = True
        g.width, g.height = 800,600
        g.graph_title = 'Despesas no Periodo'
        g.show_graph_title = True
        g.add_data({'data': data, 'title': 's'})
        return g.burn()
    def create_graph_plot2(self, data, periodo):
        g = time_series.Plot({})
        g.width, g.height = 800,600

        g.timescale_divisions = '24 hours'
        g.stagger_x_labels = True
        g.x_label_format = '%d'
        #g.max_y_value = 200
        new_data = []
        for i in range(len(periodo)):
            date_time = periodo[i]
            value = data[i]
            new_data.append(str(date_time))
            new_data.append(value)
        g.add_data({'data': new_data, 'title': 'series 1'})
        return g.burn()
    
    def index(self, tn, fo, fv, pt, df, dt, to):
        field_order = fo
        field_valor = fv
        periodo_type = pt
        data_time_from = df
        data_time_to = dt
        xy_order = to
        model_schema = model.Transacao
        model_field_order = getattr(model_schema, field_order)

        start = datetime.strptime(data_time_from, '%d-%m-%Y')
        end = datetime.strptime(data_time_to, '%d-%m-%Y')
        objects = session.query(model_schema).filter(model_field_order>=start)
        objects =                     objects.filter(model_field_order<end)
        objects = objects.order_by(model_field_order)

        periodo = []
        group_by_periodo = {}
        for item in objects:
            _item_field_order = getattr(getattr(item, field_order), periodo_type)
            item_field_order = callable(_item_field_order) and _item_field_order() or _item_field_order
            item_field_valor = getattr(item, field_valor)
            if not group_by_periodo.has_key(item_field_order):
                group_by_periodo[item_field_order] = 0.0
            group_by_periodo[item_field_order]+=float(item_field_valor)

        order_group_by_periodo = []
        despesa_periodo_keys = group_by_periodo.keys()
        despesa_periodo_keys.sort()
        for key in despesa_periodo_keys:
            order_group_by_periodo.append(group_by_periodo[key])
            periodo.append(key)
        
        periodo = list(set(periodo))
        periodo.sort()

        def sort(tx, ty):
            if xy_order.lower()=='x':
                itemx = tx[1]
                itemy = ty[1]
            else:
                itemx = tx[0]
                itemy = ty[0]

            if itemx>itemy:
               return 1
            elif itemx==itemy:
               return 0
            else: 
               return -1

        data_xy = []
        for i in range(len(order_group_by_periodo)):
            data_xy.append((order_group_by_periodo[i], periodo[i]))
        data_xy.sort(cmp=sort)
        
        data_y = [i[0] for i in data_xy]
        data_x = [str(i[1]) for i in data_xy]
        
        grafico = self.create_graph_plot(data_y, data_x)
        soup_grafico = BeautifulSoup(grafico)
        rect_xAxis = soup_grafico.findAll("rect", { "class" : "fill1" })
        tags = []
        for tag_rect in rect_xAxis:
            tag = Tag(soup_grafico, "a", [("xlink:href", 'http://www.zvon.org')])
            attr_tag_rect = [("y", tag_rect['y']),
                             ("x", tag_rect['x']),
                             ("height", tag_rect['height']),
                             ("class", tag_rect['class']),
                             ("width", tag_rect['width']),
                            ]
            new_rect = Tag(soup_grafico, "rect" , attr_tag_rect)
            tag.insert(0, new_rect)
            tags.append(tag)
            parent = tag_rect.parent
            tag_rect.extract()
            parent.insert(0, tag)
        #list_rect_xAxis = [t for t in rect_xAxis]
        #for i_tag in range(len(tags)):
        #    tag_rect = list_rect_xAxis[i_tag]
        #    tag_rect.replaceWith(tags[i_tag])
        #    #break
        #    print 'merda'
        
        cherrypy.response.headers['Content-Type'] = "text/xml"
        return open('teste', 'w').write(str(soup_grafico))
    index.exposed = True
    def grafico(self):
        context = {'schema': schema,
                    }
        return str(Template(open(self.template_chart_mount).read(), namespaces=[context]))
    grafico.exposed = True
        
